package com.example.controller.buyer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.base.BaseController;
import com.example.entity.UserAddress;
import com.example.service.UserAddressService;
import com.example.vo.LoginUser;
import com.example.vo.Result;
import com.example.vo.UserAddressVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lsc
 * @date 2024/5/12
 */
@RestController
@Slf4j
@RequestMapping("/buyer/address")
public class UserAddressController extends BaseController<UserAddressService,UserAddress> {

    @GetMapping("/getAddress")
    public Result<List<UserAddress>> getAddressByUserId(@RequestParam("userId") Integer userId){
        List<UserAddress> userAddressList = baseService.getAddressByUserId(userId);
        return Result.ok(userAddressList);
    }
    @ApiOperation(value = "获取会员收件地址")
    @GetMapping
    public Result<List<UserAddressVo>> getMemberAddress(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        List<UserAddressVo> userAddressList = baseService.getMemberAddress(id);
        return Result.ok(userAddressList);
    }


    @ApiOperation(value = "获取当前会员默认收件地址")
    @GetMapping(value = "/get/default")
    public Result<UserAddressVo> getDefaultShippingAddress() {
        return Result.ok(baseService.getDefaultMemberAddress());
    }

    @PostMapping("/addAddress")
    public Result<Boolean> addAddress(@RequestBody UserAddress userAddress){

        if(userAddress.getIsDefault()){
            Integer userId = userAddress.getUserId();
            List<UserAddress> addressList = baseService.getAddressByUserId(userId);
            for (UserAddress address : addressList) {
                if(address.getIsDefault()){
                    return Result.error("您当前已有默认地址");
                }
            }
        }

        return Result.ok(baseService.saveOrUpdate(userAddress));
    }
}